package by.sjc.grsu.web.controller;

import by.sjc.grsu.model.Account;
import by.sjc.grsu.service.AccountService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

@Controller
public class AccountController {

    public static final Logger logger = Logger.getLogger(AccountController.class);

    @Autowired
    AccountService accountService;

    @RequestMapping(value = {"", "/", "welcome"})
    public String welcome() {
        return "welcome";
    }

    @PreAuthorize("isAnonymous()")
    @RequestMapping(value = {"/login"}, method = { RequestMethod.GET })
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "message", required = false) String message) {

        ModelAndView mav = new ModelAndView();
        if (null != error)
            mav.addObject("error","Invalid username or password.");
        if (null != message)
            mav.addObject("message",message);

        mav.setViewName("login");
        return mav;
    }

//    @PreAuthorize("isAnonymous()")
//    @RequestMapping(value = {"/registration"}, method = { RequestMethod.GET })
//    public ModelAndView registration() {
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("account", new Account());
//        mav.setViewName("registration");
//        return mav;
//    }
//
//    @PreAuthorize("isAnonymous()")
//    @RequestMapping(value = {"/registration"}, method = {RequestMethod.POST})
//    public ModelAndView registration(
//            @Valid Account inputAccount,
//            BindingResult result) {
//
//        ModelAndView mav = new ModelAndView();
//        logger.info("register:" + inputAccount.toString());
//        if (result.hasErrors()) {
//            mav.setViewName("registration");
//        } else {
//            Account account = accountService.registerUserAccount(inputAccount);
//            mav.setViewName("redirect:/login");
//            mav.addObject("message","registration successful. You can log in now.");
//        }
//
//        return mav;
//    }
}
